package com.heo.pub;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import org.apache.log4j.Logger;

import com.heo.server.MainServer;
import com.heo.util.FileHelper;

public class ServerConfig
{
  private static Logger log = Logger.getLogger(ServerConfig.class);

  public static String SERVIER_ID = "00";// 控制子系统编号

  public static Date START_TIME = new Date();// 服务器启动时间

  public static int READ_IDLE_TIME = 0;// 心跳消息读超时
  public static int WRITE_IDLE_TIME = 0;// 心跳消息写超时
  public static int ALL_IDLE_TIME = 0;// 心跳消息读写超时
  public static int DEBUG_INFO = 1;// 不返回调试信息，0返回，1不返回
  public static int CONNECT_TIME_OUT = 1000;// 客户端连接超时
  public static int MAX_READABLE_BYTES_LENGTH = 0;// 等待读取字节的最大长度（防止socket流攻击，当可读的字节大于这个数字时，会跳过）

  public static int CONSOLE_PORT = 8080;// 控制台端口号
  public static String[] SOURCE_IP = null;// 访问控制台的源ip限制

  public static String CONSOLE_INDEX_TEMPLATE = null;// 控制台模版
  public static String CONSOLE_LOGIN_TEMPLATE = null;// 控制台登录模版
  public static String CONSOLE_ADMIN = null;// 控制台用户名
  public static String CONSOLE_PASSWORD = null;// 控制台密码

  public static int CONTROL_PORT = 6060;// 控制系统端口
  public static String CONTROL_URL = null;// 控制系统url
  public static String[] CONTROL_IP = null;// 哪个ip可以访问控制系统
  
  public static int DEVICE_PORT = 9999;// 硬件设备访问端口
  public static String DEVICE_URL = null;//硬件设备访问地址
  
  public static int PORT = 9786;// 监听端口号
  public static String DEVICE_TCP_IP = "";// 返回ip

  public static String SERVER_NODE = String.valueOf(new Date().getTime());// 系统当前的节点ID，只要保证唯一即可。

  public static String LAST_SEND_TIME = null;// 上次给设备发送指令的时间
  public static String LAST_RECEIVE_TIME = null;// 上次给接收设备指令的时间

  public static int RESEND_MAX_COUNT = 2;// 最大重发次数
  public static int RESEND_TIMEOUT = 100000;// 默认超时时间（从第一次发送开始计时，经过该时间后，如果发送仍然无法成功，就放弃），单位：毫秒
  public static int RESEND_INTERVAL = 30000;// 重发时间间隔，单位：毫秒。注意：这个时间不一定准确，但一定大于这个时间
  public static int RESEND_STATUS = 0;// 重发开启状态，0重发  1不重发

  public static String FIRMWARE_DIRECTORY;
  
  public static String SUB_HTTPS_URL;

  static
  {
    Properties props = new Properties();
    FileInputStream is = null;
    try
    {
    	String path = new ServerConfig().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    	is = new FileInputStream(new File(path).getParent() + "/config/server.properties");
//      is = new FileInputStream(ServerConfig.class.getResource("/").getPath() + "/com/heo/config/server.properties");
      props.load(is);
      // 控制系统编号
      SERVIER_ID = new String(props.getProperty("ServerId").getBytes("ISO8859-1"), "UTF-8");

      // 读取服务器参数
      READ_IDLE_TIME = Integer.valueOf(new String(props.getProperty("ReadIdleTime").getBytes("ISO8859-1"), "UTF-8"));
      WRITE_IDLE_TIME = Integer.valueOf(new String(props.getProperty("WriteIdleTime").getBytes("ISO8859-1"), "UTF-8"));
      ALL_IDLE_TIME = Integer.valueOf(new String(props.getProperty("AllIdleTime").getBytes("ISO8859-1"), "UTF-8"));
      PORT = Integer.valueOf(new String(props.getProperty("Port").getBytes("ISO8859-1"), "UTF-8"));
      CONNECT_TIME_OUT = Integer.valueOf(new String(props.getProperty("ConnectTimeout").getBytes("ISO8859-1"), "UTF-8"));
      MAX_READABLE_BYTES_LENGTH = Integer.valueOf(new String(props.getProperty("MaxReadableBytesLength").getBytes("ISO8859-1"), "UTF-8"));

      // 读取控制台参数
      CONSOLE_PORT = Integer.valueOf(new String(props.getProperty("ConsolePort").getBytes("ISO8859-1"), "UTF-8"));
      CONSOLE_ADMIN = new String(props.getProperty("ConsoleAdmin").getBytes("ISO8859-1"), "UTF-8");
      CONSOLE_PASSWORD = new String(props.getProperty("ConsolePassword").getBytes("ISO8859-1"), "UTF-8");

      // 读取重发参数
      RESEND_MAX_COUNT = Integer.valueOf(new String(props.getProperty("ReSendMaxCount").getBytes("ISO8859-1"), "UTF-8"));
      RESEND_TIMEOUT = Integer.valueOf(new String(props.getProperty("ReSendTimeOut").getBytes("ISO8859-1"), "UTF-8"));
      RESEND_INTERVAL = Integer.valueOf(new String(props.getProperty("ReSendInterval").getBytes("ISO8859-1"), "UTF-8"));
      RESEND_STATUS = Integer.valueOf(new String(props.getProperty("ReSendStatus").getBytes("ISO8859-1"), "UTF-8"));

      // 固件保存的位置
      FIRMWARE_DIRECTORY = new String(props.getProperty("FirmwareDirectory").getBytes("ISO8859-1"), "UTF-8");
      
      String sourceIp = new String(props.getProperty("SourceIp").getBytes("ISO8859-1"), "UTF-8");
      if (!(sourceIp == null || "".equals(sourceIp.trim())))
      {
        SOURCE_IP = sourceIp.split(",");
      }

      // 读取控制台模版
      CONSOLE_INDEX_TEMPLATE = FileHelper.getFileContent(new File(path).getParent() + "/config/console.htm");

      // 读取控制台登录模版
      CONSOLE_LOGIN_TEMPLATE = FileHelper.getFileContent(new File(path).getParent() + "/config/login.htm");

      // 读取设备控制端口
      CONTROL_PORT = Integer.valueOf(new String(props.getProperty("ControlPort").getBytes("ISO8859-1"), "UTF-8"));
      // 读取设备控制url
      CONTROL_URL = new String(props.getProperty("ControlUrl").getBytes("ISO8859-1"), "UTF-8");
      CONTROL_URL = CONTROL_URL.replaceAll("\\{ControlPort\\}", String.valueOf(CONTROL_PORT));
      sourceIp = new String(props.getProperty("ControlIp").getBytes("ISO8859-1"), "UTF-8");
      if (!(sourceIp == null || "".equals(sourceIp.trim())))
      {
        CONTROL_IP = sourceIp.split(",");
      }
      
      //硬件设备访问端口
      DEVICE_PORT = Integer.valueOf(new String(props.getProperty("DevicePort").getBytes("ISO8859-1"), "UTF-8"));
      DEVICE_TCP_IP = new String(props.getProperty("DeviceIp").getBytes("ISO8859-1"), "UTF-8");
      // 读取设备控制url
      DEVICE_URL = new String(props.getProperty("DeviceUrl").getBytes("ISO8859-1"), "UTF-8");
      DEVICE_URL = DEVICE_URL.replaceAll("\\{DeviceUrl\\}", String.valueOf(DEVICE_PORT));

      // 上次发送设备的时间
      LAST_SEND_TIME = DateFormat.getDateTimeInstance().format(new Date());
      SUB_HTTPS_URL = new String(props.getProperty("SubHttpsUrl").getBytes("ISO8859-1"), "UTF-8");
    }
    catch (IOException e)
    {
      log.error(e.getMessage(), e);
    }
    finally
    {
      if (is != null)
      {
        try
        {
          is.close();
        }
        catch (IOException e)
        {
          log.error(e.getMessage(), e);
        }
      }
    }
  }

  public static String getSourceIp()
  {
    if (SOURCE_IP == null || SOURCE_IP.length == 0)
    {
      return "无";
    }
    else
    {
      String ipStr = "";
      for (int i = 0; i < SOURCE_IP.length; i++)
      {
        ipStr = ipStr + SOURCE_IP[i] + ", ";
      }
      ipStr = ipStr.substring(0, ipStr.length() - 2);
      return ipStr;
    }
  }

  public static String getControlIp()
  {
    if (CONTROL_IP == null || CONTROL_IP.length == 0)
    {
      return "无";
    }
    else
    {
      String ipStr = "";
      for (int i = 0; i < CONTROL_IP.length; i++)
      {
        ipStr = ipStr + CONTROL_IP[i] + ", ";
      }
      ipStr = ipStr.substring(0, ipStr.length() - 2);
      return ipStr;
    }
  }

  /**
   * @param args
   */
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
  }

}
